package org.fickler

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}
import org.apache.spark.sql.functions._

object UkRoad {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("UK")
    val sc = new SparkContext(conf)

    val spark = SparkSession.builder.appName("UkRoad").getOrCreate()

    val inputPath = "src/main/java/org/datas/dft-road-casualty-statistics-accident-1979-2020.csv"
    val df = spark.read.option("header", "true").csv(inputPath)

    // 根据road_surface_conditions和accident_severity列进行分组计数
    val roadSurfaceImpact = df.groupBy("road_surface_conditions", "accident_severity")
      .agg(count("*").alias("accident_count"))
      .orderBy("road_surface_conditions", "accident_severity")

    roadSurfaceImpact.show()

    val outputPath = "src/main/java/org/UkResult/UkRoad"
    roadSurfaceImpact
      .coalesce(1)
      .write
      .mode("overwrite")
      .option("header", "true")
      .csv(outputPath)

    val mysqlUrl = "jdbc:mysql://localhost:3306/ukaccident"
    val mysqlProperties = new java.util.Properties()
    mysqlProperties.setProperty("user", "root")
    mysqlProperties.setProperty("password", "011216")
    mysqlProperties.setProperty("driver", "com.mysql.jdbc.Driver")

    roadSurfaceImpact.write
      .mode(SaveMode.Overwrite)
      .jdbc(mysqlUrl, "UkRoad", mysqlProperties)

    spark.stop()
  }

}
